package com.ruyuan.commodity.elasticsearch;

import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * 索引数据类型初始化以及商品初始化索引
 * @author kimmy
 **/
@Component
public class GoodsIndexInit implements CommandLineRunner {

    private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(GoodsIndexInit.class);

    private static final String PUT = "PUT";

    @Autowired
    private EsConfig esConfig;

    @Autowired
    private RestHighLevelClient highLevelClient;

    @Autowired
    private ResourceLoader resourceLoader;

    /**
     * 初始化商品索引索引
     * @param args
     * @throws Exception 异常信息
     */
    @Override
    public void run(String... args) throws Exception {
        String goodsIndexName = esConfig.getIndexName() + "_" + EsSettings.GOODS_INDEX_NAME;
        // 1、构造商品索引是否存在的请求
        GetIndexRequest existGoodsIndexRequest = new GetIndexRequest(goodsIndexName);
        // 2、查询商品索引是否存在
        boolean exist = highLevelClient.indices().exists(existGoodsIndexRequest, RequestOptions.DEFAULT);

        Request request;
        Response response;
        if (!exist) {
            // 3、从配置文件中获取构建商品mapping的json数据
            String initGoodsIndexJson = getCreateMappingJson();
            // 4、构造商品索引结构化mappings的请求
            request = new Request(PUT, goodsIndexName);
            request.setJsonEntity(initGoodsIndexJson);
            // 使用restful api来对商品索引进行创建
            response = highLevelClient.getLowLevelClient().performRequest(request);
            LOG.info("初始化商品索引mappings的结构的请求结果为 [{}]", EntityUtils.toString(response.getEntity()));
        }
    }

    /**
     * 获取初始化索引的json请求数据
     * @return 文件内容
     * @throws Exception 异常信息
     */
    private String getCreateMappingJson() throws Exception {
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            String createIndexJson = "";
            Resource resource = resourceLoader.getResource("classpath:initGoodsIndex.json");
            is = resource.getInputStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            StringBuffer content = new StringBuffer();
            String s = "";
            while((s = br.readLine()) != null) {
                content.append(s);
            }
            createIndexJson = content.toString();
            return createIndexJson;
        } finally {
            if (br!=null) {
                br.close();
            }
            if (isr!=null) {
                isr.close();
            }
            if (is!=null) {
                is.close();
            }
        }
    }
}
